package com.group8.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.group8.gm.GameController;

public class AddHighScorePanel extends Menu {
	private GameController gc;
	private JLabel nameLabel;
	private JTextField nameField;
	private JLabel scoreLabel;
	private JLabel actualScoreLabel;
	private JLabel title;
	private JButton saveButton;
	private JButton cancelButton;
	
	private int actualScore;
	public AddHighScorePanel(GameController gc) {
		this.gc = gc;
		setPreferredSize(new Dimension(800, 660));
		setLayout(null);
		title = new JLabel("Congrats! You are in the top 5");
		title.setFont(new Font("HighScoreFont", Font.PLAIN, 40));
		title.setForeground(Color.RED);
		title.setBounds(100, 20 , title.getPreferredSize().width, title.getPreferredSize().height);
		
		//Labels
		Font fn = new Font("Label Font", Font.PLAIN, 30);
		nameLabel = new JLabel("Your name: ");
		nameLabel.setFont(fn);
		nameLabel.setForeground(Color.RED);
		nameLabel.setBounds(100, 120, nameLabel.getPreferredSize().width, nameLabel.getPreferredSize().height);
		
		scoreLabel = new JLabel("Your score is: ",SwingConstants.RIGHT);
		scoreLabel.setFont(fn);
		scoreLabel.setForeground(Color.RED);
		scoreLabel.setBounds(nameLabel.getBounds().x + nameLabel.getBounds().width - scoreLabel.getPreferredSize().width, 320, scoreLabel.getPreferredSize().width, scoreLabel.getPreferredSize().height);
		
		//Name Input
		nameField = new JTextField(30);
		nameField.setForeground(Color.BLUE);
		nameField.setBounds(nameLabel.getBounds().x + nameLabel.getBounds().width + 10, 120, 400, nameLabel.getBounds().height);
		nameField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
		
		
		//Actual score Label
		
		actualScoreLabel = new JLabel("10000000000000", SwingConstants.LEFT);
		actualScoreLabel.setFont(fn);
		actualScoreLabel.setForeground(Color.BLUE);
		actualScoreLabel.setBounds(nameField.getBounds().x, scoreLabel.getBounds().y, actualScoreLabel.getPreferredSize().width, actualScoreLabel.getPreferredSize().height);
		
		
		SaveHandler handler = new SaveHandler();
		//Save Button
		saveButton = new JButton();
		saveButton.addActionListener(handler);
		Image img = new ImageIcon("assets/save.png").getImage();
		saveButton.setIcon(new ImageIcon(img));
		
		saveButton.setBounds(350,598, 86,40);
		
		//Cancel Button
		cancelButton = new JButton();
		cancelButton.addActionListener(handler);
		Image img2 = new ImageIcon("assets/cancel.png").getImage();
		cancelButton.setIcon(new ImageIcon(img2));
		
		cancelButton.setBounds(500,500,105,40);
		
		add(title);
		add(nameLabel);
		add(scoreLabel);
		add(nameField);
		add(actualScoreLabel);
		add(saveButton);
		add(cancelButton);
	}
	
	public void setActualScore(int score) {
		this.actualScore = score;
		this.actualScoreLabel.setText(Integer.toString(score));
	}
	
	public int getActualScore() {
		return this.actualScore;
	}
	
	private class SaveHandler implements ActionListener{
		@SuppressWarnings("unchecked")
		public void actionPerformed(ActionEvent e) {
			if(e.getSource() == saveButton) {
				JSONObject objectToBeAdded = new JSONObject();
				objectToBeAdded.put("username",nameField.getText());
				objectToBeAdded.put("hscore", actualScore);
				
				JSONArray jsonArray = new JSONArray();
				JSONParser parser = new JSONParser();
				try {
					Object obj = parser.parse(new FileReader("assets/highscores.json"));
					jsonArray = (JSONArray) obj;
				} catch(Exception e1) {
					e1.printStackTrace();
				}
				
				Iterator<JSONObject> iterator = jsonArray.iterator();
				int itemCount = 0;
				boolean isFound = false;
				
				while(iterator.hasNext()) {
					JSONObject jsonObj = iterator.next();
					long longScoreVal = (long)jsonObj.get("hscore");
					if((int)longScoreVal <= actualScore) {
						jsonArray.add(itemCount, objectToBeAdded);
						isFound = true;
						break;
					}
					itemCount++;
				}
				
				if(!isFound)
					jsonArray.add(objectToBeAdded);
				
				try {
					FileWriter file = new FileWriter("assets/highscores.json");
					file.write(jsonArray.toJSONString());
					file.close();
				} catch (Exception e2) {
					// TODO: handle exception
					e2.printStackTrace();
				}
				gc.returnToMain();
			} else {
				gc.returnToMain();
			}
		}
	}
	
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Image img = new ImageIcon("assets/trophy.png").getImage();
		g.drawImage(img, 0, 0, null);
	}
}
